# -*- coding: utf-8 -*-
import json
from flask_admin import BaseView, expose
from flask import flash, url_for, redirect, request, current_app
from flask_wtf import FlaskForm
from wtforms import TextAreaField
from adminApp.views import MyCusView
from adminApp.extensions import redis_store
import json


class AppConfigForm(FlaskForm):
    config_json = TextAreaField('',render_kw={'placeholder':'接收警报，微信参数配置，json格式','rows':'30'})


class AppConfigView(MyCusView):

    @expose('/', methods=('GET', 'POST'))
    def index(self):
        form = AppConfigForm(request.form)
        cfg_path = current_app.config.get('RD_WEIXIN_CFG')
        if request.method == 'POST' and form.validate():
            cfg = form.config_json.data
            try:
                ojs = json.loads(cfg)
                redis_store.set(current_app.config.get('RD_WEIXIN_CFG'), json.dumps(ojs, indent=1))
                return redirect(url_for('.index'))
            except:
                flash('不能转换为json格式','error')
        else:
            try:
                val = json.dumps(json.loads(redis_store.get(current_app.config.get('RD_WEIXIN_CFG'))))
            except:
                val = None
            form.config_json.data=val
        return self.render('novel/appconfig.html',form=form)